const http = require('http');
const fs = require('fs');
const url = require('url');
const io = require('socket.io');

let httpServer = http.createServer((req, res) => {

  let {
    pathname
  } = url.parse(req.url);
  let rs = fs.createReadStream(`www${pathname}`);

  rs.pipe(res);

  rs.on('error', err => {
    res.writeHeader(404);
    res.write('Not Found');
    res.end();
  });

});

httpServer.listen(8080);

// ws监听httpserver
let wsServer = io.listen(httpServer);

let aSock = [];
wsServer.on('connection', sock => {
  aSock.push(sock);

  // 断开连接
  sock.on('disconnect', () => {
    let n = aSock.indexOf(sock);
    if (n != -1) {
      aSock.splice(n, 1);
    }
    // sock.emit('count', aSock.length);
  });

  // sock.emit('count', aSock.length);

  sock.on('msg', str => {
    aSock.forEach(s => {
      if (s != sock) {
        s.emit('msg', str);
        // console.log();
      } else {
        console.log(aSock.indexOf(s));
      }
    });

  });
  setInterval(function() {
    sock.emit('count', aSock.length);
  }, 1000);
});
